﻿using System;
using Microsoft.VisualStudio.SharePoint;
using Microsoft.VisualStudio.SharePoint.Explorer;
using CodeCounsel.SharePoint.DevTools.Commands;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.SharePoint.Explorer.Extensions;

namespace CodeCounsel.SharePoint.DevTools.ExplorerNodeExtensions
{
    [Export(typeof(IExplorerNodeTypeProvider)),
    ExplorerNodeType(NodeIDs.FeatureDependencyNode)]
    public class FeatureDependencyNodeTypeProvider
        : IExplorerNodeTypeProvider
    {
        internal static void CreateFeatureDependencyNodes(IExplorerNode parentNode)
        {
            IFeatureNodeInfo info = parentNode.ParentNode.GetAnnotation<IFeatureNodeInfo>();
            FeatureInfo featureDetails = new FeatureInfo()
            {
                FeatureID = info.Id
            };
            FeatureDependencyInfo[] dependencies =
                parentNode.Context.SharePointConnection.ExecuteCommand<FeatureInfo, FeatureDependencyInfo[]>(CommandIDs.GetFeatureDependencies, featureDetails);
            foreach (FeatureDependencyInfo dependency in dependencies)
            {
                CreateNode(parentNode, dependency);
            }
        }

        internal static IExplorerNode CreateNode(IExplorerNode parentNode, FeatureDependencyInfo dependency)
        {
            Dictionary<object, object> annotations = new Dictionary<object, object>();
            annotations.Add(typeof(FeatureDependencyInfo), dependency);
            return parentNode.ChildNodes.Add(NodeIDs.FeatureDependencyNode, String.Format("{0} ({1})", dependency.Title, dependency.MinimumVersion), annotations);
        }

        public void InitializeType(IExplorerNodeTypeDefinition typeDefinition)
        {
            typeDefinition.IsAlwaysLeaf = true;
        }
    }
}
